package com.atguigu.qqzone.service.impl;

import com.atguigu.qqzone.dao.TopicDAO;
import com.atguigu.qqzone.pojo.Reply;
import com.atguigu.qqzone.pojo.Topic;
import com.atguigu.qqzone.pojo.UserBasic;
import com.atguigu.qqzone.service.TopicService;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: TopicServiceImpl
 * @Description:
 * @Author: wty
 * @Date: 2022/12/9
 */

public class TopicServiceImpl implements TopicService {
    private TopicDAO topicDAO;
    /**
     * 引入ReplyServiceImpl
     */
    private ReplyServiceImpl replyServiceImpl;
    private UserBasicServiceImpl userBasicServiceImpl;

    @Override
    public List<Topic> getTopicList(UserBasic userBasic) {
        String sqlStr = "SELECT a.* FROM qqzonedb2.`t_topic` a INNER JOIN qqzonedb2.`t_user_basic` b ON a.`author` = b.`id` AND a.`author` = ?";
        ArrayList<Topic> list = new ArrayList<>();
        return topicDAO.queryMultiListAndMap(sqlStr, list, userBasic.getId());
    }

    @Override
    public void addTopic(Topic topic) {
        String sqlStr = "INSERT INTO qqzonedb2.`t_topic` VALUES (0,?,?,?,?)";
        topicDAO.dml(sqlStr, topic.getTitle(), topic.getContent(), topic.getTopicDate(), topic.getAuthor().getId());
    }

    @Override
    public void delTopic(Topic topic) {
        String sqlStr = "DELETE FROM qqzonedb2.`t_topic` WHERE id = ?";
        topicDAO.dml(sqlStr, topic.getId());
    }

    @Override
    public void delTopic(Integer id) {
        Topic topic = getTopic(id);
        if (null != topic) {
            // 删除所有日志中的回复
            replyServiceImpl.delReplyList(topic);

            // 删除所有日志
            delTopic(topic);
        }
    }

    @Override
    public Topic getTopic(Integer id) {
        String sqlStr = "SELECT * FROM qqzonedb2.`t_topic` a WHERE a.`id` = ?";
        Topic topic = topicDAO.querySingleTopic(sqlStr, id);
        UserBasic author = topic.getAuthor();
        author = userBasicServiceImpl.getUserBasicById(author.getId());
        topic.setAuthor(author);
        return topic;
    }

    @Override
    public Topic getTopicById(Integer id) {
        Topic topic = getTopic(id);

        List<Reply> replyList = replyServiceImpl.getReplyListByTopicId(topic.getId());
        topic.setReplyList(replyList);

        return topic;
    }
}
